package com.ficus.road.maintain.controller;

import com.ficus.road.maintain.core.model.statistic.StatisticByTypeRequest;
import com.ficus.road.maintain.core.model.statistic.StatisticMonthRequest;
import com.ficus.road.maintain.core.model.statistic.StatisticMonthResponse;
import com.ficus.road.maintain.dto.StatusStatisticResponse;
import com.ficus.road.maintain.service.HitStatisticService;
import com.ficus.road.maintain.util.DateUtil;
import com.ficus.road.maintain.util.MyDateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@RestController
@Slf4j
@RequiredArgsConstructor
public class HitStatisticController {

    private final HitStatisticService hitStatisticService;

    //月度病害统计
    @RequestMapping(value = "/hits/statistic/trend/month",
            produces = {"application/json"},
            consumes = {"application/json"},
            method = RequestMethod.POST)
    public ResponseEntity<List<StatisticMonthResponse>> trendMonth(@RequestBody StatisticMonthRequest request) {
        if (StringUtils.isEmpty(request.getStartMonth())) {
            request.setStartMonth(MyDateUtil.dateFormatStr(DateUtil.after(new Date(), Calendar.MONTH, -6), "yyyy-MM"));
        }
        if (StringUtils.isEmpty(request.getEndMonth())) {
            request.setEndMonth(MyDateUtil.dateFormatStr(new Date(), "yyyy-MM"));
        }
        return new ResponseEntity<>(hitStatisticService.trendMonth(request), HttpStatus.OK);
    }

    @RequestMapping(value = "/hits/statistic/type/top",
            produces = {"application/json"},
            consumes = {"application/json"},
            method = RequestMethod.POST)
    public ResponseEntity<List<StatusStatisticResponse>> statisticByType(@Valid @RequestBody StatisticByTypeRequest request) {
        if (Objects.isNull(request.getEndTime())) {
            request.setEndTime(System.currentTimeMillis() / 1000);
        }
        if (Objects.isNull(request.getStartTime())) {
            request.setStartTime(DateUtil.getMonthStart(new Date()).getTime() / 1000);
        }
        return new ResponseEntity<>(hitStatisticService.statisticByType(request), HttpStatus.OK);
    }
}
